package utils;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class MayiktJdbcUtils {
    //1.需要将我们的构造方法私有化---工具类 不需要new出来 是通过类名来访问的
    private MayiktJdbcUtils() {

    }

    //2.定义工具类需要的声明变量
    private static String driverClass;
    private static String url;
    private static String user;
    private static String password;

    static {
        try {
            //3.使用到静态代码块 来给我们声明好多 jdbc变量赋值(读取)
            //1.读取config.properties
            InputStream resourceAsStream = MayiktJdbcUtils.class.getClassLoader().getResourceAsStream("config.properties");
            //2.赋值给我们声明好的变量
            Properties properties = new Properties();
            properties.load(resourceAsStream);
            driverClass = properties.getProperty("driverClass");
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            password = properties.getProperty("password");
            //3.注册驱动类
            Class.forName(driverClass);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    //4.封装连接方法
    public static Connection getConnection() throws SQLException {
        try{
            return DriverManager.getConnection(url, user, password);
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }
    //5.封装释放连接方法

    //1.查 Connection ResultSet Statement
    public static void closeConnection(Connection connection, Statement statement, ResultSet resultSet) {
        try {
            if (connection != null)
                connection.close();
            if (statement != null)
                statement.close();
            if (resultSet != null)
                resultSet.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //2.增删改 Connection Statement 方法重载
    public static void closeConnection(Connection connection, Statement statement) {
        closeConnection(connection, statement, null);
    }

    /*
    * 开启事务 就是关闭sql的自动提交
    *
    * */
    public static void beginTransaction(Connection connection) throws SQLException {
        connection.setAutoCommit(false);
    }
    /*
    * 提交事务
    * */
    public static void commitTransaction(Connection connection) throws SQLException {
        connection.commit();
    }
    /*
    * 回滚事务
    * */
    public static void rollbackTransaction(Connection connection)  {
        if (connection!=null) {
            try {
                connection.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
//    public static void main(String[] args) {
//        System.out.println(MayiktJdbcUtils.driverClass);
//    }
}